package main

import (
	"fmt"
	"log"
	"sync"
	"time"
)

type jobManager struct {
	sync.RWMutex
	activeJobs map[string]deployJob
}

func (j *jobManager)jobUpdate(jm *jobManager,jobs ...deployJob) {
	// 临时map，用于存储每次传入的新数据
	tmp := make(map[string]deployJob)

	for _,job := range jobs {
		name := job.getname()
		// 如果map中没有key为name的数据，添加并调用start
		if _, ok := jm.activeJobs[name]; !ok {
			jm.Lock()
			jm.activeJobs[name] = job
			jm.Unlock()
			job.start()
		}
		// 由于jm.activeJobs有老数据未删除，通过tmp map记录新数据，然后对比
		tmp[name] = job
	}

	// 对比新传入的map 和 jm.activeJobs，删除老数据
	for k,v := range jm.activeJobs{
		if _,ok := tmp[k];!ok{
			v.stop()
			delete(jm.activeJobs,k)
		}
	}
}
type deployJob interface {
	getname()string
	start()
	stop()
}

type k8sDeploy struct {
	name string
}

type nodeDeploy struct {
	name string
}
// 获取name 作为map 的 key
func (k *k8sDeploy)getname()string  {
	return k.name
}
func (k *k8sDeploy)start()  {
	log.Printf("JobName:%s JobStatus:starting\n",k.name)
}
func (k *k8sDeploy)stop()  {
	log.Printf("JobName:%s JobStatus:stoping\n",k.name)
}

func (n *nodeDeploy)getname()string  {
	return n.name
}

func (n *nodeDeploy)start() {
	log.Printf("JobName:%s JobStatus:starting\n",n.name)
}
func (n *nodeDeploy)stop()  {
	log.Printf("JobName:%s JobStatus:stoping\n",n.name)
}

func main() {
	job1 := &k8sDeploy{name: "k8sjob1"}
	job2 := &k8sDeploy{name: "k8sjob2"}
	job3 := &k8sDeploy{name: "nodejob1"}
	job4 := &nodeDeploy{name: "nodejob2"}

	jm:=&jobManager{}
	jm.activeJobs = make(map[string]deployJob)

	jm.jobUpdate(jm,job1,job2)
	time.Sleep(time.Second*2)
	fmt.Println("======================")
	jm.jobUpdate(jm,job2,job3,job4)
	time.Sleep(time.Second*2)
	fmt.Println("======================")
	jm.jobUpdate(jm,job3)
}

// 